package com.quant.controller;

import com.quant.entity.BacktestAll;
import com.quant.entity.BacktestResult;
import com.quant.service.BacktestService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/backtest")
@RequiredArgsConstructor
public class BacktestController {

	private final BacktestService backtestService;

	/**
	 * 执行均线交叉策略回测
	 */
	@PostMapping("/ma-cross")
	public BacktestResult runMaCrossStrategy(
			@RequestParam(defaultValue = "600036.SH,601318.SH") String stocks,
			@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
			@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
			@RequestParam(defaultValue = "1000000.0") double initialCapital,
			@RequestParam(defaultValue = "10") int shortWindow,
			@RequestParam(defaultValue = "30") int longWindow,
			@RequestParam(defaultValue = "0.8") double positionRatio) {

		List<String> stockList = Arrays.asList(stocks.split(","));
		return backtestService.runMaCrossStrategy(stockList, startDate, endDate, initialCapital, shortWindow, longWindow, positionRatio);
	}

	/**
	 * 执行RSI策略回测
	 */
	@PostMapping("/rsi")
	public BacktestResult runRsiStrategy(
			@RequestParam(defaultValue = "600036.SH,601318.SH") String stocks,
			@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
			@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
			@RequestParam(defaultValue = "1000000.0") double initialCapital,
			@RequestParam(defaultValue = "75") double overbought,
			@RequestParam(defaultValue = "25") double oversold,
			@RequestParam(defaultValue = "0.8") double positionRatio) {

		List<String> stockList = Arrays.asList(stocks.split(","));
		return backtestService.runRsiStrategy(stockList, startDate, endDate, initialCapital, overbought, oversold, positionRatio);
	}


	/**
	 * 统一回测入口（适配前端/api/backtest/start请求）
	 */
	@PostMapping("/start")
	public ResponseEntity<BacktestResult> startBacktest(@Valid @RequestBody BacktestAll request) {
		// 解析请求参数
		List<String> stockList = request.getStockPool().stream()
				.map(stock -> stock.getCode())
				.collect(Collectors.toList());

		LocalDate startDate = LocalDate.parse(request.getTimeRange().getStartDate());
		LocalDate endDate = LocalDate.parse(request.getTimeRange().getEndDate());
		double initialCapital = request.getInitialCapital();

		// 根据策略类型执行对应回测
		switch (request.getStrategyType()) {
			case "MA_CROSS":
				BacktestResult maResult = backtestService.runMaCrossStrategy(
						stockList,
						startDate,
						endDate,
						initialCapital,
						request.getStrategyParams().getShortTermMA(),
						request.getStrategyParams().getLongTermMA(),
						request.getPositionManagement().getMaxPositionPerStock() / 100.0  // 转换为比例
				);
				return ResponseEntity.ok(maResult);
			case "RSI":
				BacktestResult rsiResult = backtestService.runRsiStrategy(
						stockList,
						startDate,
						endDate,
						initialCapital,
						request.getStrategyParams().getRsiOverbought(),
						request.getStrategyParams().getRsiOversold(),
						request.getPositionManagement().getMaxPositionPerStock() / 100.0  // 转换为比例
				);
				return ResponseEntity.ok(rsiResult);
			default:
				throw new IllegalArgumentException("不支持的策略类型: " + request.getStrategyType());
		}
	}

}
